package com.mitou.common.config;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.mitou.base.entity.BaseUser;
import com.mitou.common.utils.web.BaseContextUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 针对于实体字段保存至数据库的拦截处理器，进行特定字段的赋值
 * e.g. @TableField(value = "create_time", fill = FieldFill.INSERT)
 *
 * @author rice
 * @see com.baomidou.mybatisplus.annotation.TableField
 * @since 2021-06-09
 */
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Resource
    private BaseContextUtil baseContextUtil;

    @Override
    public void insertFill(MetaObject metaObject) {
        BaseUser loginUser = baseContextUtil.getLoginUser();
        Date date = new Date();
        Long userId = loginUser.getUserId();
        String userName = loginUser.getUserName();
        this.setFieldValByName("createTime", date, metaObject);
        this.setFieldValByName("updateTime", date, metaObject);
        this.setFieldValByName("createUserId", userId, metaObject);
        this.setFieldValByName("createUserName", userName, metaObject);
        this.setFieldValByName("updateUserId", userId, metaObject);
        this.setFieldValByName("updateUserName", userName, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        BaseUser loginUser = baseContextUtil.getLoginUser();
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateUserId", loginUser.getUserId(), metaObject);
        this.setFieldValByName("updateUserName", loginUser.getUserName(), metaObject);
    }
}

